package com.jstyle.jclife.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayoutManager;
import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.blesdk.model.GetData;
import com.jstyle.blesdk.model.SetTime;
import com.jstyle.blesdk.model.StepModel;
import com.jstyle.jclife.BuildConfig;
import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.R;
import com.jstyle.jclife.activity.ActivityHistoryActivity;
import com.jstyle.jclife.activity.BindDeviceActivity;
import com.jstyle.jclife.activity.BindDeviceListActivity;
import com.jstyle.jclife.activity.ExerciseRecordListActivity;
import com.jstyle.jclife.activity.HeartHistoryActivity;
import com.jstyle.jclife.activity.HistoryActivity;


import com.jstyle.jclife.activity.ManageLoginActivity;
import com.jstyle.jclife.activity.SleepHistoryActivity;
import com.jstyle.jclife.activity.UserInfoActivity;
import com.jstyle.jclife.adapter.HomePageAdapter;
import com.jstyle.jclife.adapter.RecyclerViewBaseAdapter;
import com.jstyle.jclife.app.MyApplication;
import com.jstyle.jclife.ble.BleManager;
import com.jstyle.jclife.daoManager.BindDeviceInfoDaoManager;
import com.jstyle.jclife.daoManager.HeartDataDaoManager;
import com.jstyle.jclife.daoManager.LastActivityDataDaoManager;
import com.jstyle.jclife.daoManager.PathRecordDaoManager;
import com.jstyle.jclife.daoManager.SleepDataDaoManager;
import com.jstyle.jclife.daoManager.StepDataDaoManager;
import com.jstyle.jclife.daoManager.UserInfoDaoManager;
import com.jstyle.jclife.model.BindDeviceInfo;
import com.jstyle.jclife.model.Device1810;
import com.jstyle.jclife.model.HeartData;
import com.jstyle.jclife.model.JstyleDevice;
import com.jstyle.jclife.model.LastActivityData;
import com.jstyle.jclife.model.PathRecord;
import com.jstyle.jclife.model.SleepData;
import com.jstyle.jclife.model.StepData;
import com.jstyle.jclife.model.UserInfo;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.GlobalConst;
import com.jstyle.jclife.utils.ImageUtils;
import com.jstyle.jclife.utils.ResolveData;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.utils.SharedPreferenceUtils;
import com.jstyle.jclife.utils.Utils;
import com.jstyle.jclife.view.CircleProgress;
import com.jstyle.jclife.view.HeadCircleView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.disposables.Disposable;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HomePageFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomePageFragment extends BaseFragment implements RecyclerViewBaseAdapter.OnItemClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.RecyclerView_home)
    RecyclerView RecyclerViewHome;
    Unbinder unbinder;
    @BindView(R.id.iv_icon_homepage)
    ImageView ivIconHomepage;
    @BindView(R.id.tv_username)
    TextView tvUsername;

    @BindView(R.id.iv_product_homepage)
    ImageView ivProductHomepage;
    @BindView(R.id.iv_syc_homepage)
    ImageView ivSycHomepage;
    @BindView(R.id.tv_homepage_date)
    TextView tvHomepageDate;
    @BindView(R.id.tv_health_heart)
    ImageView ivDataDay;
    @BindView(R.id.CircleProgress_homepage)
    CircleProgress CircleProgressHomepage;
    @BindView(R.id.rl_homepage_top)
    RelativeLayout rlHomepageTop;
    @BindView(R.id.tv_home_recordDay)
    TextView tvHomeRecordDay;
    @BindView(R.id.ll_exercise)
    LinearLayout llExercise;
    @BindView(R.id.tv_home_sleepTime)
    TextView tvHomeSleepTime;
    @BindView(R.id.ll_sleep)
    LinearLayout llSleep;

    @BindView(R.id.SleepCircleProgress)
    com.jstyle.jclife.view.SleepCircleProgress SleepCircleProgress;
    public final static String ACTION_UPDATE_GOA = "ACTION_UPDATE_GOA";
    @BindView(R.id.tv_homepage_title)
    TextView tvHomepageTitle;
    @BindView(R.id.view_divider)
    View viewDivider;
    @BindView(R.id.tv_email_alert)
    TextView tvEmailAlert;
    @BindView(R.id.iv_health)
    ImageView ivHealth;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private Disposable subscription;
    private HomePageAdapter homePageAdapter;

    public HomePageFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomePageFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomePageFragment newInstance(String param1, String param2) {
        HomePageFragment fragment = new HomePageFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    int lastHeart = 0;

    private void init() {
        Log.i(TAG, "init: ");


        ScreenUtils.setBigTitleTypeface(tvHomepageTitle);

        final String address = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        HeartData heartData = HeartDataDaoManager.getLastHeartData();
        if (heartData != null) {
            lastHeart = heartData.getHeart();
        }
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(getActivity());
        LastActivityData lastActivityData = LastActivityDataDaoManager.getLastActivityData();

        List<String> list = new ArrayList<>();
        list.add(getString(R.string.cal_laber));
        list.add(ResolveData.getDistanceLabel());
        list.add(getString(R.string.hr_laber));
        list.add(getString(R.string.Active_Minutes));
        list.add(getString(R.string.Exercise_Minutes));
        homePageAdapter = new HomePageAdapter(list);
        String[] data = new String[5];
        data[0] = "0";
        data[1] = "0";
        data[2] = lastHeart == 0 ? "--" : String.valueOf(lastHeart);
        data[3] = "00:00";
        data[4] = "0";
        if (lastActivityData != null && !TextUtils.isEmpty(address)) {
            String date = lastActivityData.getDate();
            String today = DateUtil.getDefaultFormatTime(new Date());
            if (date.equals(today)) {
                data[0] = lastActivityData.getCal();
                data[1] = lastActivityData.getDistance();
                data[2] = String.valueOf(lastHeart);
                data[3] = lastActivityData.getActivityTime();
                data[4] = lastActivityData.getExerciseTime();
                int stepGoal = SharedPreferenceUtils.getInteger(SharedPreferenceUtils.KEY_Step_goal, 10000);
                CircleProgressHomepage.updateGoal(Integer.valueOf(lastActivityData.getStep()), stepGoal);
            }
        } else {
            int stepGoal = SharedPreferenceUtils.getInteger(SharedPreferenceUtils.KEY_Step_goal, 10000);
            CircleProgressHomepage.updateGoal(0, stepGoal);
        }
        homePageAdapter.setDatas(data);
        homePageAdapter.setOnItemClickListener(this);
        RecyclerViewHome.setLayoutManager(layoutManager);
        RecyclerViewHome.setAdapter(homePageAdapter);
        getSleepData();
        changeUi();
    }

    private void changeUi() {
        JstyleDevice jstyleDevice = MyApplication.getJstyleDevice();
        if (jstyleDevice instanceof Device1810) {
            ivDataDay.setVisibility(View.INVISIBLE);
            ivHealth.setVisibility(View.VISIBLE);
        } else {
            ivDataDay.setVisibility(View.VISIBLE);
            ivHealth.setVisibility(View.INVISIBLE);
        }
    }

    private void findSportRecordData() {
        JstyleDevice jstyleDevice = MyApplication.getJstyleDevice();
        if (jstyleDevice instanceof Device1810) {
            showGoalDays();
        } else {
            List<PathRecord> pathRecordList = PathRecordDaoManager.getAllPathRecord();
            List<String> dateList = new ArrayList<>();
            for (PathRecord pathRecord : pathRecordList) {
                String mDate = pathRecord.getMDate();
                String date = mDate.split(" ")[0];
                //     Log.i(TAG, "findSportRecordData: " + mDate + " " + date);
                if (!dateList.contains(date)) dateList.add(date);
            }
            tvHomeRecordDay.setText(String.format(getString(R.string._7), dateList.size()));
        }

    }

    @Override
    public void onResume() {
        super.onResume();

        updateConnectStatus(BleManager.getInstance().isConnected());
        findSportRecordData();
        updateUserInfo();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i(TAG, "onSaveInstanceState: ");
        saveLastData();
    }

    private void saveLastData() {
        String[] datas = homePageAdapter.getDatas();
        LastActivityData lastActivityData = LastActivityDataDaoManager.getLastActivityData();
        final String address = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        if (TextUtils.isEmpty(address)) return;
        lastActivityData.setAddress(address);
        lastActivityData.setCal(datas[0]);
        lastActivityData.setDistance(datas[1]);
        lastActivityData.setActivityTime(datas[3]);
        lastActivityData.setExerciseTime(datas[4]);
        lastActivityData.setStep(String.valueOf(CircleProgressHomepage.getLastStep()));
        lastActivityData.setDate(DateUtil.getDefaultFormatTime(new Date()));
        LastActivityDataDaoManager.insertLastActivityData(lastActivityData);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (!hidden) {
            Log.i(TAG, "onHiddenChanged: home " + hidden);
            StepModel stepModel = new StepModel();
            stepModel.setStepState(true);
            sendData(SendCmdState.SET_STEP_MODEL, stepModel);
            findSportRecordData();
            init();
            updateUserInfo();
        }
    }

    boolean disallow;

    public void updateUserInfo() {
        if (!isAdded()) return;
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(NetWorkUtil.getUserId());
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(NetWorkUtil.getUserId());
            UserInfoDaoManager.insertUser(userInfo);
        }
        Uri iconUri = ImageUtils.getIconUri(getActivity(), userInfo.getUserId());
        String userName = userInfo.getName();
        Bitmap bmHead = ImageUtils.findHeadBitmap(getActivity(), iconUri);
        bmHead = bmHead == null ? BitmapFactory.decodeResource(getActivity().getResources(),
                R.drawable.user_icon) : bmHead;
        HeadCircleView circleView = new HeadCircleView(bmHead);
        if (ivIconHomepage == null) return;
        ivIconHomepage.setImageDrawable(circleView);
        if (TextUtils.isEmpty(userName)) userName = GlobalConst.KEY_DefaultName;
        tvUsername.setText(userName);

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.i(TAG, "onAttach: ");
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        saveLastData();
        unbinder.unbind();
    }

    @Override
    public void onItemClick(int position) {
        if (Utils.isFastClick()) {
            return;
        }
        Intent intent = new Intent(getActivity(), HistoryActivity.class);
        int dataType = 0;
        switch (position) {
            case 0:
                dataType = HistoryActivity.DATA_CAL;
                break;
            case 1:
                dataType = HistoryActivity.DATA_DISTANCE;
                break;
            case 2:
                Intent intentHeart = new Intent(getActivity(), HeartHistoryActivity.class);
                startActivity(intentHeart);
                return;
            case 3:
                dataType = HistoryActivity.DATA_SPORT_TIME;
                break;
            case 4:
                dataType = HistoryActivity.DATA_EXERCISE_TIME;
                break;
        }
        intent.putExtra(HistoryActivity.KEY_DATA_TYPE, dataType);
        startActivity(intent);
    }


    private static final String TAG = "HomePageFragment";

    @OnClick(R.id.CircleProgress_homepage)
    public void onViewClicked() {

    }

    @OnClick({R.id.tv_email_alert, R.id.iv_product_homepage, R.id.iv_icon_homepage, R.id.ll_exercise, R.id.ll_sleep, R.id.iv_syc_homepage, R.id.tv_health_heart, R.id.CircleProgress_homepage})
    public void onViewClicked(View view) {
        if (Utils.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_email_alert:
                startActivity(ManageLoginActivity.class);
                break;
            case R.id.iv_icon_homepage:
                startActivity(UserInfoActivity.class);
                break;
            case R.id.iv_product_homepage:
//                if (!BleManager.getInstance().isConnected()){
//
//                }
                String deviceAddress = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
                List<BindDeviceInfo> bindDeviceInfoList = BindDeviceInfoDaoManager.queryAllData();
                startActivity(bindDeviceInfoList.size() == 0 ? BindDeviceActivity.class : BindDeviceListActivity.class);

                break;
            case R.id.ll_exercise:
                JstyleDevice jstyleDevice = MyApplication.getJstyleDevice();
                if (jstyleDevice instanceof Device1810) {
                    startActivity(ActivityHistoryActivity.class);
                } else {
                    startActivity(ExerciseRecordListActivity.class);
                }

                break;
            case R.id.ll_sleep:
                startActivity(SleepHistoryActivity.class);
                break;
            case R.id.iv_syc_homepage:
                if (isBleEnable()) {
                    setTime();
                } else {
                    enableBle();
                }
//                StepModel stepModel=new StepModel();
//                stepModel.setStepState(true);

                // BleManager.getInstance().writeValue(SingleDealData.sendData(SendCmdState.SET_STEP_MODEL,stepModel));

                break;
            case R.id.tv_health_heart:
                startActivity(ActivityHistoryActivity.class);
                break;
            case R.id.CircleProgress_homepage:
                startActivity(HistoryActivity.class);
                break;
        }
    }

    public void setTime() {
        SetTime setTime = new SetTime();
        boolean sendSuccess = sendData(SendCmdState.GET_DEVICE_Time);
        if (sendSuccess) {
            showProgressDialog(getString(R.string.Data_Synchronizing));
        } else {
            connect();
        }
    }

    public void startSycData() {
        GetData getData = new GetData();
        getData.setDataNum(0);
        boolean sendSuccess = sendData(SendCmdState.GET_STEP_DATA, getData);
        if (sendSuccess) {
            showProgressDialog(getString(R.string.Data_Synchronizing));
        } else {
            connect();
        }
    }

    private void getSleepData() {
        String today = DateUtil.getDefaultFormatTime(new Date());
        String queryDate = DateUtil.getYesterdayDateString(today);//第一次查询昨天睡觉数据
        String lastDate = DateUtil.getTomorrowDateString(queryDate);
        List<SleepData> sleepDataList = SleepDataDaoManager.queryData(queryDate, lastDate);
        int[] fiveSleepData = new int[288];//288*5分钟

        for (int i = 0; i < fiveSleepData.length; i++) {
            fiveSleepData[i] = -1;//睡眠数据0为有效数据
        }
        if (sleepDataList.size() == 0) {
            SleepCircleProgress.setSleepTime(fiveSleepData, -1, -1);
            tvHomeSleepTime.setText(DateUtil.getPointSleepTime(getActivity(), 0));
            return;
        }
        for (SleepData sleepData : sleepDataList) {
            String time = sleepData.getTime();
            String data = sleepData.getDateString();
            int startCount = DateUtil.get5MIndex(time, queryDate + " 12:00:00");
            if (startCount >= 288) break;
            fiveSleepData[startCount] = Integer.valueOf(data) == 0 ? (int) (5 + Math.random() * 15) : Integer.valueOf(data);
        }
        List<Integer> sleepTime = getSleepData(fiveSleepData);
        if (sleepTime.size() >= 2) {
            int count = sleepTime.size() / 2;
            int duration = 0;
            for (int i = 0; i < count; i++) {
                duration += sleepTime.get(i * 2 + 1) - sleepTime.get(i * 2);
            }
            SleepCircleProgress.setSleepTime(fiveSleepData, sleepTime.get(0), sleepTime.get(sleepTime.size() - 1));
            int sleepTotal = sleepTime.get(sleepTime.size() - 1) - sleepTime.get(0);
            tvHomeSleepTime.setText(DateUtil.getPointSleepTime(getActivity(), duration * 5));
        } else {
            SleepCircleProgress.setSleepTime(fiveSleepData, -1, -1);
            tvHomeSleepTime.setText(DateUtil.getPointSleepTime(getActivity(), 0));
        }

    }

    private List<Integer> getSleepData(int[] fiveSleepData) {
        List<Integer> list = new ArrayList<>();
        int goBed = -1;
        int upBed = 0;
        int offCount = 0;
        for (int i = 0; i < fiveSleepData.length; i++) {
            int data = fiveSleepData[i];
            if (data != -1) {
                offCount = 0;
                if (goBed == -1) {
                    list.add(i);
                    goBed = i;
                }

            } else {
                offCount++;
                if (offCount == 6 && goBed != -1) {//30分钟离床
                    list.add(i - 5);
                    offCount = 0;
                    goBed = -1;
                }
            }
            if (i == fiveSleepData.length - 1 && goBed != -1) {
                list.add(i);
            }
        }
        return list;
    }

    private void connect() {
        showProgressDialog(getString(R.string.connectting));
        final String address = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        BleManager.getInstance().connectDevice(address);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    /**
     * 更新实时运动数据
     *
     * @param maps
     */
    public void updateActivityData(Map<String, String> maps) {
        String step = maps.get(DeviceKey.KTotalSteps);
        String cal = maps.get(DeviceKey.KCalories);
        String distance = maps.get(DeviceKey.KDistance);
        String time = maps.get(DeviceKey.KSportTime);
        String heart = maps.get(DeviceKey.KHeartValue);
        String exerciseTime = maps.get(DeviceKey.KExerciseTime);
        Log.i(TAG, "updateActivityData: " + cal);
        String[] data = new String[5];
        data[0] = cal;
        data[1] = ResolveData.getShowDistance(distance);
        data[2] = Integer.valueOf(heart) == 0 ? String.valueOf(lastHeart) : heart;
        data[3] = DateUtil.getActivityTime(Integer.valueOf(time));
        data[4] = DateUtil.getActivityShowTime(Integer.valueOf(exerciseTime));
        homePageAdapter.setDatas(data);
        int stepGoal = SharedPreferenceUtils.getInteger(SharedPreferenceUtils.KEY_Step_goal, 10000);
        CircleProgressHomepage.updateGoal(Integer.valueOf(step), stepGoal);
    }

    public void updateConnectStatus(boolean connect) {
        if (!connect) disMissProgressDialog();
        ivProductHomepage.setImageResource(connect ? R.drawable.device_connect : R.drawable.device_disconnect);
    }

    public void updateGoal() {
        int stepGoal = SharedPreferenceUtils.getInteger(SharedPreferenceUtils.KEY_Step_goal, 10000);
        CircleProgressHomepage.updateGoal(stepGoal);
    }

    public void updateActivateState(boolean isActivate) {
        if (BuildConfig.APPLICATION_ID.equals("com.jstyle.fomofit")) {
            tvEmailAlert.setVisibility(isActivate ? View.GONE : View.VISIBLE);
        }

    }

    public void saveFinish() {
        getSleepData();
        disMissProgressDialog();
    }

    private void showGoalDays() {
        List<StepData> stepDataLis = StepDataDaoManager.queryAllData();
        int goalDays = 0;
        for (StepData stepData : stepDataLis) {
            int goal = Integer.parseInt(stepData.getGoal());
            Log.i(TAG, "showGoalDays: " + stepData.getDate() + " " + goal + " " + stepData.getStep());
            if (goal >= 50) goalDays++;
        }
        tvHomeRecordDay.setText(String.format(getString(R.string._7), goalDays));

    }

    public void changeDevice() {
        changeUi();
    }
}
